package com.sky.yipinyoufujava.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.yipinyoufujava.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求拦截器
 */
@Slf4j
@Component
public class RequestFilter implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    /**
     * boolean   true = 放行   false = 不放行
     */
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
        String token = request.getHeader("Token");
        /**
         * 强制转换类型
         */
        log.info("获取到的令牌,{}",token);
//        验证令牌
        try {
//            从redis中获取token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if(redisToken == null){
//                空的token
                throw new RuntimeException();
            }
            log.info("令牌有效！",token);
            Map<String,Object> claims = JwtUtil.parseToken(token);
            return true;
        } catch (Exception e){
            log.error("令牌过期或无效！", token, e);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            // 创建一个Map来保存错误信息
            Map<String, Object> errorInfo = new HashMap<>();
            errorInfo.put("msg", "error");
            errorInfo.put("data", "登录过期，重新登录！");
            errorInfo.put("code", response.getStatus());
            // 将错误信息转换为JSON字符串
            String jsonErrorInfo = new ObjectMapper().writeValueAsString(errorInfo);
            // 使用response输出流将错误信息发送给前端
            try (PrintWriter out = response.getWriter()) {
                out.print(jsonErrorInfo);
                out.flush();
            } catch (IOException ex) {
                log.error("Error writing response", ex);
            }
            return false;
        }
    }
}
